package il.ac.tau.dbcourse.gui;

import il.ac.tau.dbcourse.db.reports.IncompleteAlbum.AlbumDetails;
import il.ac.tau.dbcourse.freedb.FreeDbParser;
import il.ac.tau.dbcourse.logic.MP3Scanner;
import il.ac.tau.dbcourse.logic.MixAndMatch;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.swing.UnsupportedLookAndFeelException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.xml.sax.SAXException;

public class MainGui {
	final static int NUMBEROFFREEDBLINES = 1000;
	final static Boolean DEBUG = true;
	final static Display display = new Display();
	final static Shell shell = new Shell(display);
	public static MyProperties properties;

	

	public static void main(String[] args) {
		properties = new MyProperties();
		properties.init();
		final int buttonSpacingWidth = 15;
		final int buttonSpacingHeight = 15;
		Image image = new Image(shell.getDisplay(),
				"Images/logo.jpg");

		shell.setText("Find My Missing Songs And Albums");
		GridLayout grid = new GridLayout();
		grid.horizontalSpacing = buttonSpacingWidth;
		grid.makeColumnsEqualWidth = true;
		grid.numColumns = 1;
		grid.verticalSpacing = buttonSpacingHeight;
		grid.marginWidth = buttonSpacingWidth;
		grid.marginHeight = buttonSpacingHeight;

		shell.setLayout(grid);
		final Button updateDbButton = new Button(shell, SWT.PUSH);
		Button runButton = new Button(shell, SWT.PUSH);
		Button run2Button = new Button(shell, SWT.PUSH);

		shell.setSize(600, 400);
		String lastUpdatedDate = properties
				.getProperty("lastUpdatedFreedbDate");// "today";
		updateDbButton.setText(" Update Local Copy Of FreeDB (last updated: "
				+ lastUpdatedDate + ")");
		updateDbButton.setImage(image);
		updateDbButton.setLayoutData(new GridData(GridData.FILL_BOTH));

		runButton.setText(" Scan My HardDrive And Find My Missing Songs");
		runButton.setLayoutData(new GridData(GridData.FILL_BOTH));
		runButton.setSize(updateDbButton.getSize());

		run2Button.setText(" Find results based on last scan ");
		run2Button.setLayoutData(new GridData(GridData.FILL_BOTH));
		run2Button.setSize(updateDbButton.getSize());

		updateDbButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				shell.setEnabled(false);

				FileDialog dialog = new FileDialog(shell, SWT.NULL);
				final String path = dialog.open();
				if (path != null) {
					File file = new File(path);
					if (file.isFile()) {
						final ProgressBarWindow pbw = ProgressBarWindow.initProgressBar(shell,"Updating FreeDB...");
						final Thread main = new Thread() {
							public void run() {
								String[] params = { (String) path, "--truncate", "--max:250000" };
								try {
									FreeDbParser.main(params, pbw
											.getPrintStream());
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						};
						ProgressBarWindow.startProgressOn(pbw, main);

						DateFormat dateFormat = new SimpleDateFormat(
								"dd/MM/yyyy HH:mm:ss");
						java.util.Date date = new java.util.Date();
						String datetime = dateFormat.format(date);
						properties.setProperty("lastUpdatedFreedbDate",
								datetime);
						String lastUpdatedDate2 = properties
								.getProperty("lastUpdatedFreedbDate");
						updateDbButton
								.setText(" Update Local Copy Of FreeDB (last updated: "
										+ lastUpdatedDate2 + ")");
						updateDbButton.redraw();
					} else {
					}

				}
				shell.setEnabled(true);

			}
		});

		runButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {

				DirectoryDialog fileDialog = new DirectoryDialog(shell,
						SWT.OPEN);
				fileDialog.setText("Select Root Directory For Scan:");
				final String path = fileDialog.open();

				if (path != null) {
					Dialog myDialog = new Dialog(
							shell,
							"Are you sure you want to scan all subdirectories of\r\n"
									+ path
									+ "\r\n and compare that to freedb to find your missing mp3 songs?\r\n\r\n(this will remove the result of last scan from memory and might take a few minutes)");
					if (myDialog.getResult()) {
						final ProgressBarWindow pbw = ProgressBarWindow.initProgressBar(shell,"Scanning your HD for mp3's...");
						final Thread main = new Thread() {
							public void run() {
								try {
									MP3Scanner.scan(new File(path), pbw
											.getPrintStream());
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						};
						ProgressBarWindow.startProgressOn(pbw, main);

						final ProgressBarWindow pbw2 = ProgressBarWindow.initProgressBar(shell,"Mixing and Matching your mp3's to freedb...");
						final Thread main2 = new Thread() {
							public void run() {
								try {
									MixAndMatch mixAndMatch = new MixAndMatch();
									mixAndMatch.mix();

									//List<AlbumDetails> albums = mixAndMatch
									//		.getIncompleteAlbums();
									
									mixAndMatch.close();

								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						};
						ProgressBarWindow.startProgressOn(pbw2, main2);

						DateFormat dateFormat = new SimpleDateFormat(
								"dd/MM/yyyy HH:mm:ss");
						java.util.Date date = new java.util.Date();
						String datetime = dateFormat.format(date);
						properties.setProperty("lastScanDirectory", path);
						properties.setProperty("lastScanDate", datetime);
						Shell resultWindowShell = new Shell(shell);
						try {
							new ResultWindow(resultWindowShell);
						} 
						catch (InterruptedException e1) {
							e1.printStackTrace();
						} catch (XPathExpressionException e1) {
							e1.printStackTrace();
						} catch (ParserConfigurationException e1) {
							e1.printStackTrace();
						} catch (SAXException e1) {
							e1.printStackTrace();
						} catch (IOException e1) {
							e1.printStackTrace();
						} catch (ClassNotFoundException e1) {
							e1.printStackTrace();
						} catch (InstantiationException e1) {
							e1.printStackTrace();
						} catch (IllegalAccessException e1) {
							e1.printStackTrace();
						} catch (UnsupportedLookAndFeelException e1) {
							e1.printStackTrace();
						}
					}
				}
			}
		});
		run2Button.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				Shell resultWindowShell = new Shell(shell);
				try {
					new ResultWindow(resultWindowShell);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				} catch (XPathExpressionException e1) {
					e1.printStackTrace();
				} catch (ParserConfigurationException e1) {
					e1.printStackTrace();
				} catch (SAXException e1) {
					e1.printStackTrace();
				} catch (IOException e1) {
					e1.printStackTrace();
				} catch (ClassNotFoundException e1) {
					e1.printStackTrace();
				} catch (InstantiationException e1) {
					e1.printStackTrace();
				} catch (IllegalAccessException e1) {
					e1.printStackTrace();
				} catch (UnsupportedLookAndFeelException e1) {
					e1.printStackTrace();
				}
				while (!resultWindowShell.isDisposed()) {
					if (!display.readAndDispatch())
						display.sleep();
				}
			}
		});

		shell.pack();
		shell.setMinimumSize(shell.getSize());
		shell.setSize(600, 250);
		shell.open();

		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
					display.sleep();
			}
		display.dispose();
	}
}
